var async = require('async');
var parking = mongoose.model('parking');

function validateParkingStatus(userwish, callback) {
    var wishId = userwish._id;
    var status = userwish.status ? userwish.status : "";
    if (!userwish.status || !userwish.dateExpired || !userwish.wish || typeof userwish.wish != "object" || !userwish.wish.minSupport) {
        getParkingFunc({_id: wishId}, function (err, result) {
            status = userwish.status;
            if (!err && result != null) {
                checkParkingStatus(userwish);
            }
            if (status != userwish.status) {
                console.log("CHANGE IN WISH STATUS",wishId,status,"->>>",userwish.status);
                updateParkingFunc({_id: wishId}, {'status': userwish.status}, callback);
            } else
                callback(err, userwish);
        })
    } else {
        checkParkingStatus(userwish);
        if (status != userwish.status) {
            console.log("CHANGE IN WISH STATUS",wishId,status,"->>>",userwish.status);
            updateParkingFunc({_id: wishId}, {'status': userwish.status}, callback);
        } else
            callback(null, userwish);
    }
}

function checkParkingStatus(userwish) {
    var status = userwish.status;
    var expiryDate = new Date(userwish.dateExpired);
    var curDate = new Date();
    if (status != WISH_STATUS[1])
        return;
    if (userwish.wish && userwish.supporters.length > userwish.wish.minSupport) {
        userwish.status = WISH_STATUS[2];
    }
    else if (curDate > expiryDate) {
        userwish.status = WISH_STATUS[3];
    }
}

function addParkingDetail(data, callback) {
    if (data.supporters)
        data.supportCount = data.supporters.length;
    if (data.status == WISH_STATUS[4] || data.status == WISH_STATUS[3])
        return;
    if (data.dateExpired) {
        var expiryDate = new Date(data.dateExpired);
        var curDate = new Date();
        if (expiryDate > curDate) {
            var timeLeft = (expiryDate - curDate) / (36e5 * 24);
            var daysLeft = Math.floor(timeLeft);
            var hoursLeft = (timeLeft - daysLeft) * 24;
            var minutesLeft = ((hoursLeft - Math.floor(hoursLeft)) * 60);
            var secondsLeft = ((minutesLeft - Math.floor(minutesLeft)) * 60);
            data.timeLeft = {
                days: daysLeft,
                hours: Math.floor(hoursLeft),
                minutes: Math.floor(minutesLeft),
                seconds: Math.floor(secondsLeft)
            }
        }
    }
    validateParkingStatus(data, callback);
}

var wishPopulate = 'desc minSupport maxDays images';

function getParkingFunc(query, callback) {
    UserParking.findOne(query).populate('wish', wishPopulate).exec(function (err, result) {
        if (!err && result != null) {
            addParkingDetail(result, function () {
            });
        }
        callback(err, result);
        updateParkingFunc({_id:result._id}, {"$inc":{"browseCount":1}}, function(){});
    })
}

function getParkingListFunc(query, callback) {
    UserParking.find(query).sort({_id:-1}).populate('wish', wishPopulate).exec(function (err, result) {
        if (!err && result != null) {
            var lenn = result.length;
            for (var i = 0; i < lenn; ++i) {
                addParkingDetail(result[i], function () {
                });
            }
        }
        callback(err, result);
    })
}

function updateParkingFunc(query, updateObj, callback) {
    UserParking.update(query, updateObj).exec(callback);
}

exports.getParkingListService = function (ts, direction, callback) {
    var opt = {
        isValid: true,
    };

    if (direction == 'top') {
        opt.dateCreated = {$gt: new Date(Number(ts))}
    } else if (direction == 'down') {
        opt.dateCreated = {$lt: Number(ts)}
    }

    if (ts == '0') {
        delete  opt.dateCreated;
    }

    console.log('getParkingListService', opt);

    var batchSize = 10;

    parking.find(opt, 'phone price wechatUserInfo.nickName wechatUserInfo.avatarUrl location pAddress pName dateCreated category').limit(batchSize).sort('-dateCreated')
        .exec(function (err, results) {
            var data = {};

            if (!results  || results.length == 0) {
                if (direction == 'top') {
                    data.latestTs = ts;
                } else {
                    data.nextTs = ts;
                    data.nomoredata = 1;
                }
                data.list = [];
                callback(null, data);
                return;
            }

            //下拉刷新返回数据
            if (direction == 'top') {

                if (ts != '0') {
                    var count = results.length < batchSize ? results.length : results.length + Math.ceil(Math.random() * 5);
                    data.refreshMsg = '更新了' + count + '条帖子';
                } else {
                    data.nextTs = results[results.length - 1].dateCreated.getTime();
                }

                //返回最新时间戳
                data.latestTs = results[0].dateCreated.getTime();
            } else {

                if (results.length < batchSize) {
                    data.nomoredata = 1;
                }

                data.nextTs = results[results.length - 1].dateCreated.getTime();
            }


            data.list = results;
            callback(null, data);
    })
};

exports.getParkingDetailService = function (wishId, callback) {
    getParkingFunc({'_id': wishId}, callback);
};

exports.getUserParkingListService = function (wechatId, callback) {
    getParkingListFunc({'createdBy': wechatId}, callback);
};

exports.getUserSupportedParkingListService = function (wechatId, callback) {
    getParkingListFunc({'supporters': wechatId}, callback);
};

exports.getJingxuanParkingListService = function (callback) {
    getParkingListFunc({type: WISH_TYPE[2]}, callback);
};

exports.makeParkingService = function (user, input, callback) {

    var temp = new parking();
    var curdate = new Date();
    // var expiryDate = new Date(curdate);
    // expiryDate.setDate(expiryDate.getDate() + result.maxDays);

    temp.createdBy = null;
    temp.wechatUserInfo = input.userInfo;

    temp.dateCreated = curdate;
    temp.dateLastModified = temp.dateCreated;

    // temp.dateExpired = expiryDate;
    temp.isValid = true;

    temp.community = null;

    temp.pName = input.pName;
    temp.pAddress = input.pAddress;
    temp.location = {
        longitude: input.longitude,
        latitude: input.latitude
    }
    temp.category = input.category;
    temp.price = input.price;
    temp.phone = input.phone;

    temp.save(callback);
};

exports.updateParkingService = function (wishId, input, callback) {
    updateParkingFunc({_id: wishId}, input, callback);
};

exports.removeParkingService = function (wishId, callback) {
    updateParkingFunc({_id: wishId}, {isValid: false}, callback);
    //UserParking.remove({_id: wishId});
};

exports.solvedParkingService = function (wishId, callback) {
    updateParkingFunc({_id: wishId}, {status: WISH_STATUS[4]}, callback);
};

exports.addParkingSupporterService = function (user, wishId, callback) {
    updateParkingFunc({_id: wishId}, {
        $addToSet: {'supporters': user},  // don't use push, since push can result in duplicates
        dateLastModified: new Date()
    }, callback);
};

exports.removeParkingSupporterService = function (user, wishId, callback) {
    updateParkingFunc({_id: wishId}, {
        $pull: {'supporters': user},
        dateLastModified: new Date()
    }, callback);
};

exports.shareParkingService = function (user, wishId, callback) {
    //
};
